import { Component, OnInit,Input,Output,EventEmitter,SimpleChange } from '@angular/core';

@Component({
  selector: 'app-pagination',
  templateUrl: './pagination.component.html',
  styleUrls: ['./pagination.component.css']
})
export class PaginationComponent implements OnInit {

  @Input() total:number;
  @Input() page:number;
  @Output() pagination=new EventEmitter<{page:number,pageSize:number}>();
   sizeArray:Array<number>=[10,20,30,50,100];
   pageSize:number=10;
   totalPage:number;
  
  /**
   * 初始化设定page:1,pageSize:10
   * [constructor description]
   */
  constructor() { 

     this.page=this.page||1;
     this.pageSize=this.pageSize||10;

   }

  ngOnInit() {

     //向上舍入计算总页数
     this.totalPage=Math.ceil(this.total / this.pageSize);
     console.log('pageSize:',this.pageSize);
  }

  /**
   * 改变pageSize
   * [setPageSize description]
   */
  setPageSize(){

     this.page=1;
     //向上舍入计算总页数
     this.totalPage=Math.ceil(this.total / this.pageSize);
     this.pagination.emit({page:1,pageSize:this.pageSize});
     console.log('pageSize:',this.pageSize);
  }
  
  /**
   * 上一页
   * [previous description]
   */
  previous(){

     if(this.page===1) return; 
     this.page--;
     this.pagination.emit({page:this.page,pageSize:this.pageSize});

  }

  /**
   * 下一页
   * [next description]
   */
  next(){

     if(this.page===this.totalPage) return;
     this.page++;
     this.pagination.emit({page:this.page,pageSize:this.pageSize});
  }
  
  /**
   * 跳转到首页
   * [first description]
   */
  first(){
   
    //防止重复请求 if(this.page===1) return;
     this.page=1;
     this.pagination.emit({page:1,pageSize:this.pageSize});
  }
  
  /**
   * 跳转到末页
   * [last description]
   */
  last(){
    
    //防止重复请求 if(this.page===this.totalPage) return; 
    this.page=this.totalPage;
    this.pagination.emit({page:this.totalPage,pageSize:this.pageSize});
  }

  /**
   * 输入属性的值发生变化,外部的total发生变化后 重新渲染分页组件
   * [ngOnChanges description]
   */
  ngOnChanges(changes:{[propKey:string]:SimpleChange}){
        console.log('changes:',changes)
       for (let propName in changes) {
        
         if(propName!='total') break;

         let changedProp = changes[propName];
         let to = JSON.stringify(changedProp.currentValue);
         console.log(propName,changedProp);
         if (changedProp.isFirstChange()) {
            console.log('pagination输入属性第一次发生变化');
         } else {
            console.log('pagination输入属性再次发生变化');
           
            //向上舍入计算总页数
            this.pageSize=10;
            this.page=1;
            this.totalPage=Math.ceil(this.total / this.pageSize);
            this.pagination.emit({page:this.page,pageSize:this.pageSize});

         }
       }
  }


}
